<?php

namespace App\Services;

use App\Models\Mini\MaintainModel;

class RepairsService extends BaseService
{
    protected $user;

    public function __construct()
    {
        $this->user = auth('user')->user();
    }

    /**
     * Notes: 添加报修
     * User: lstink
     * Date: 2021/3/4
     * Time: 6:08 下午
     * @param $data
     * @return array
     */
    public function addRepairs($data): array
    {
        $data['user_id'] = $this->user['id'];
        $data['c_id'] = $this->user['community_id'];
        $data['e_id'] = $this->user['property_id'];
        $data['created_at'] = time();
        $result = MaintainModel::create($data);
        return $result ? $this->format($result) : $this->format_error($result);
    }

    /**
     * Notes: 获取用户的报修列表
     * User: lstink
     * Date: 2021/3/5
     * Time: 9:45 上午
     * @return array
     */
    public function getRepairsListByUserId($params): array
    {
        $result = MaintainModel::where(['user_id' => $this->user['id'], 'is_cancel' => '0'])->where(function ($query) use ($params) {
            if (!empty($params) && isset($params['status'])) {
                $query->where('status', $params['status']);
            }
        })->get();
        return $result ? $this->format($result) : $this->format_error('暂无数据');
    }

    /**
     * Notes: 取消报修
     * User: lstink
     * Date: 2021/3/5
     * Time: 10:03 上午
     * @param $id
     * @return array
     */
    public function cancelRepairs($id): array
    {
        $info = MaintainModel::where(['id' => $id, 'user_id' => $this->user['id']])->first();
        if (!$info) {
            return $this->format_error('数据不存在');
        }
        if ($info['status'] == 1) {
            return $this->format_error('已完成数据不能取消');
        }
        $info->is_cancel = '1';
        $result = $info->save();

        return $result ? $this->format([]) : $this->format_error('取消失败');
    }

    /**
     * Notes: 报修详情
     * User: lstink
     * Date: 2021/3/5
     * Time: 10:56 上午
     * @param $id
     * @return array
     */
    public function detail($id): array
    {
        $info = MaintainModel::where(['id' => $id, 'user_id' => $this->user['id']])->first();
        return $info ? $this->format($info) : $this->format_error('数据不存在');
    }
}
